from PySide2.QtCore import Slot

from forms.uipy.UI_IndexFind import Ui_IndexFinde
from PySide2.QtWidgets import QWidget
from server.IndexFindServer import IndexFindServer
from PySide2.QtGui import QStandardItemModel, QStandardItem, QKeySequence,QClipboard
from tools.File_Select_Tools import File_Select_Tools
from PySide2.QtCore import Qt,QItemSelectionModel
from functools import cmp_to_key

class IndexFindImpl(QWidget, Ui_IndexFinde):
    """
    指标查找工具
    """

    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # 加载显示项数据
        self.index_dir_btn.clicked.connect(self.__index_dir_btn_handler)

        self.ok_run.clicked.connect(self.__ok_run_handler)

        # 设置表格
        # self.show_table.setHorizontalHeader()
        # 设置季度数据
        self.task.addItem("一季度",userData=1)
        self.task.addItem("二季度",userData=2)
        self.task.addItem("三季度",userData=3)
        self.task.addItem("四季度",userData=4)
        self.task.setCurrentText("一季度")

    def __index_dir_btn_handler(self):
        index_path = File_Select_Tools.select_dir(title="指标目录选择")
        self.index_dir_path.setText(index_path)
        self.index_obj = IndexFindServer(index_path)
        # 获取所有可视化项
        self.index_item_show.addItems(self.index_obj.show_item_data())

    def __get_indexs(self):
        """
        获取指标集合
        :return:
        """
        if not self.index_code.text():
            return []
        if "," in self.index_code.text():
            temp = []
            for e in self.index_code.text().split(","):
                temp.append(int(e))
            return temp

        else:
            return [int(self.index_code.text())]

    def keyPressEvent(self, event):
        # 重写键盘按下事件
        if event.matches(QKeySequence.StandardKey.Copy):
            select_items = self.show_table.selectedIndexes()
            if len(select_items) > 0:
                # 使用cmp_to_key转换, 排序
                select_items = sorted(select_items, key=cmp_to_key(self.__sort_select_items))
                # 行数
                row_num = select_items[0].row()

                min_row = select_items[0].row()
                max_row = select_items[-1].row()
                min_col = select_items[0].column()
                temp_min_col = min_col
                max_col = select_items[-1].column()
                # for item in select_items:
                #     if item.row() == row_num:
                #         str = str + item.data() + "\t"
                #     else:
                #         str = str + "\n" + item.data()+"\t"
                #         row_num = item.row()
                str_arr =[]
                while min_row <= max_row:
                    row = []
                    while temp_min_col <= max_col:
                        flag = 0
                        for item in select_items:
                            if item.row() == min_row and item.column() == temp_min_col:
                                row.append(item.data())
                                flag = 1
                                break
                        if flag == 0:
                            row.append("")
                        temp_min_col += 1
                        flag = 0
                    temp_min_col = min_col
                    str_arr.append(row)
                    min_row += 1
                # 添加到剪切板
                # 将二维数组转化为字符串
                # 添加到剪贴板数据
                str = ""
                for row in str_arr:
                    for col in row:
                        str += col + "\t"
                    str += "\n"
                # print(str)
                # 获取剪切板对象
                QClipboard().setText(str)
                # print(min_row,max_row)
                # print(min_col,max_col)
    def __sort_select_items(self,a,b):
        """
        自定义排序选择数据 1 0 -1
        :param a: 当前项
        :param b: 后一项
        :return:
        """
        if a.row() < b.row():
            return -1
        elif a.row() == b.row():
            # 同行，排序列
            if a.column() < b.column():
                return -1
            elif a.column() == b.column():
                return 0
            else:
                return 1
        else:
            return 1
    def deal_actionCopy_triggered(self):
        pass
    def __ok_run_handler(self):

        data = self.index_obj.get_data(self.__get_indexs(), self.task.currentData(),
                                       self.index_item_show.currentText())
        # 创建模型
        self.model = QStandardItemModel()

        self.model.setHorizontalHeaderLabels(list(data.keys()))
        for indexRow, row in data.iterrows():
            indexColumn = 0
            for column in row:
                temp_item = QStandardItem(str(column))
                temp_item.setTextAlignment(Qt.AlignCenter)
                # 禁止编辑
                temp_item.setEditable(False)
                self.model.setItem(indexRow, indexColumn, temp_item)
                indexColumn += 1
        self.show_table.setModel(self.model)


        # 使列宽度自适应
        self.show_table.resizeColumnsToContents()
